<?php
/**
 * Created by mq.
 * User: mq
 * Date: 17-9-3
 * Time: 下午10:07
 */

namespace app\admin\controller;

use common\controller\AdminBase;
use http\Env\Request;
use think\Cache;
use think\Db;
use think\File;
use think\Loader;
use think\Session;
use tool\auth;

class Index extends AdminBase
{

    private $uploads_path = ROOT_PATH . 'public' . DS . 'uploads';
    private $fileSize = 5548576;

    public function index()
    {
        $this->goods_list();
        return $this->fetch('goods_list');
    }

    public function goods_list()
    {
        $list = Db::table('goods')->paginate(10);
        $page = $list->render();
        $this->assign('list', $list);
        $this->assign('page', $page);
        $this->assign('page_num', $list->currentPage());
        return $this->fetch();
    }

    public function goods_add()
    {

        if (request()->isPost()) {
            $data = request()->request();
            $model = $data['model'];
            $images = isset($data['path']) ? $data['path'] : false;

            $id = 0;

            if ($images) {

                if ($model) {
                    Db::table('goods')->insert(['model' => $model, 'add_date' => time(), 'sum_img' => count($images)]);
                    $id = Db::table('goods')->getLastInsID();
                } else {
                    $this->error('产品型号不能为空！');
                }

                foreach ($images as $key => $path) {
                    Db::table('goods_images')->insert(['img' => $path, 'goods_id' => $id]);
                }

                if ($id) $this->qr($id, $model);//生成二维码
                $this->success('新增商品成功', 'goods_add');
            } else {
                $this->error('请先上传商品图片！');
            }

            $this->error('新增商品失败');
        }
        return $this->fetch();
    }

    public function image_upload()
    {

        $res = ['code' => 0, 'msg' => '上传失败！'];

        if ($this->request->isPost()) {
            $files = request()->file('file');
            if ($files) {
                $info = $files->validate(['size' => $this->fileSize, 'ext' => 'jpg,png,gif'])->move(ROOT_PATH . 'public' . DS . 'uploads');
                if ($info) {
                    // 成功上传后 获取上传信息
                    // 输出 jpg
                    $info->getExtension();
                    // 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
                    $res['path'] = $info->getSaveName();
                } else {
                    // 上传失败获取错误信息
                    $error[] = $files->getError();
                }

                if (empty($error)) {
                    $res['code'] = 200;
                    $res['msg'] = '上传成功';
                }
            }
        }

        return $res;
    }

    public function goods_edit($id, $p)
    {

        $images = Db::table('goods_images')->where(['goods_id' => $id])->select();

        if (request()->isPost()) {
            $post = request()->request();
            $model = $post['model'];
            $_iids = !empty($post) && isset($post['iid']) ? $post['iid'] : 0;
            $sum_img = count($images);

            $files = request()->file();

            if ($id) {
                $error = [];
                $iids = [];

                foreach ($images as $image) {
                    $iid = $image['id'];
                    $info = $files && isset($files['replace_' . $iid]) ? $files['replace_' . $iid] : false;

                    $iids[] = $iid;

                    if (!$info || empty($info)) continue;

                    $rep_file = $info->validate(['size' => $this->fileSize, 'ext' => 'jpg,png,gif'])->move(ROOT_PATH . 'public' . DS . 'uploads');

                    if ($rep_file) {
                        // 成功上传后 获取上传信息
                        // 输出 jpg
                        $rep_file->getExtension();
                        // 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
                        $path = $rep_file->getSaveName();
                        Db::table('goods_images')->where('id', $iid)->update(['img' => $path]);
                    } else {
                        // 上传失败获取错误信息
                        $error[] = $rep_file->getError();
                    }
                }

                if ($_iids) {
                    $diff = array_diff($iids, $_iids);
                    $sum_img = $sum_img - count($diff);
                    if (!empty($diff)) Db::table('goods_images')->delete($diff);
                }


                if ($files && isset($files['images'])) {
                    foreach ($files['images'] as $file) {

                        $info = $file->validate(['size' => $this->fileSize, 'ext' => 'jpg,png,gif'])->move(ROOT_PATH . 'public' . DS . 'uploads');
                        if ($info) {
                            // 成功上传后 获取上传信息
                            // 输出 jpg
                            $info->getExtension();
                            // 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
                            $path = $info->getSaveName();
                            Db::table('goods_images')->insert(['img' => $path, 'goods_id' => $id]);
                        } else {
                            // 上传失败获取错误信息
                            $error[] = $file->getError();
                        }

                        $sum_img++;
                    }
                }

                if ($model) Db::table('goods')->where('id', $id)->update(['model' => $model, 'sum_img' => $sum_img, 'update_date' => time()]);

                if (empty($error)) {
//                    print_r(request()->request('p'));exit;
                    $this->success('修改商品成功', url('goods_list'));
                } else {
                    $this->error(implode(',', $error));
                }
            }

        } else {
            $item = Db::table('goods')
                ->where(['id' => $id])
                ->find();
        }

        $this->assign('item', $item);
        $this->assign('images', $images);
        $this->assign('goods_id', $id);
        $this->assign('page', $p);

        return $this->fetch();
    }

    public function admin_list()
    {
        $list = Db::table('admin')->where(['super' => 0])->paginate(10);
        $page = $list->render();
        $this->assign('list', $list);
        $this->assign('page', $page);

        return $this->fetch();
    }

    public function create_qr($id)
    {
        if ($id) {
            $info = Db::table('goods')->where('id', $id)->find();
            $this->qr($id, $info['model']);
            $this->success('生成二维码成功！');
        } else {
            $this->error('生成二维码失败！');
        }
    }

    public function goods_del($id)
    {
        if ($id) {
            $req = Db::table('goods')->where(['id' => $id])->delete();

            $images = Db::table('goods_images')->where(['goods_id' => $id])->select();

            foreach ($images as $img) {
                $path = $this->uploads_path . DS . $img['img'];
                if (file_exists($path)) unlink($path);
            }

            Db::table('goods_images')->where(['goods_id' => $id])->delete();

            if ($req) {
                $this->success('删除成功！');
            } else {
                $this->success('删除失败！');
            }

        }
    }

    public function config()
    {

        $data = $this->request->request();

        $music = [];

        if (!empty($data) && $this->request->isPost()) {
            foreach ($data as $key => $val) {
                if (isset($data[$key])) {
                    if ($key == 'music') {
                        foreach ($data[$key] as $m) $music[] = $m;
                        Cache::set($key, $music);
                    } else {
                        Cache::set($key, $val);
                    }
                }

                if (!isset($data['music'])) Cache::set('music', []);
            }
            $this->success('设置成功！', url('config'), 0, 0);
        }

        $this->assign('domain', Cache::get('domain'));
        $this->assign('music', Cache::get('music'));

        return $this->fetch();
    }

    public function add_music()
    {
        if ($this->request->isPost()) {

            $file = $this->request->file('music');
            $music = Cache::get('music');
            $music = is_array($music) ? $music : [];
            if ($file && !empty($file)) {
                $info = $file->validate(['size' => $this->fileSize, 'ext' => 'mp3'])->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'music');
                if ($info) {
                    // 成功上传后 获取上传信息
                    // 输出 jpg
                    $info->getExtension();
                    // 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
                    $path = $info->getSaveName();

                    $music[] = $path;
                    Cache::set('music', $music);
                } else {
                    // 上传失败获取错误信息
                    $error[] = $file->getError();
                }

                if (!empty($error)) {
                    $this->error(implode(',', $error));
                } else {
                    $this->success('添加音乐成功！', url('config'), 0, 0);
                }
            }


        }

        return $this->fetch();
    }

    public function add_admin()
    {
        if (request()->isPost()) {
            $data = request()->request();
            $name = $data && isset($data['name']) ? trim($data['name']) : null;
            $pass = $data && isset($data['pass']) ? trim($data['pass']) : null;

            $formVerify = $this->validate(
                $data,
                ['name' => 'require', 'pass' => 'require'],
                ['username' => '用户名不能为空', 'password' => '密码不能为空', 'verify' => '验证码不能为空']
            );

            if ($formVerify !== true) $this->error($formVerify);

            if ($name && $pass) {
                $pass = md5(md5($pass) . md5(config('web_key')));

                $id = Db::table('admin')->insert(['username' => $name, 'password' => $pass]);

                if ($id) {
                    $this->success('添加管理员成功！');
                } else {
                    $this->error('添加管理员失败！');
                }
            }
        }

        return $this->fetch();
    }

    public function del_admin($uid)
    {
        $uid = intval($uid);
        if ($uid) {
            Db::table('admin')->where('id', $uid)->delete();
            $this->success('删除成功', url('index/admin_list'));
        } else {
            $this->error('非法操作！');
        }

    }

    public function update_password()
    {
        if (request()->isPost()) {
            $data = request()->request();
            $formVerify = $this->validate(
                $data,
                ['o_password' => 'require', 'password' => 'require'],
                ['o_password' => '旧密码不正确', 'password' => '新密码不能为空']
            );

            if (!is_login()) $this->error('请先登录！');
            if ($formVerify !== true) $this->error($formVerify);
            $user_id = Session::get('user.id');
            $user_info = Db::table('admin')->where('id', $user_id)->find();

            $o_password = md5(md5($data['o_password']) . md5(config('web_key')));
            if ($user_info['password'] != $o_password) $this->error('旧密码错误！');

            $new_password = md5(md5($data['password']) . md5(config('web_key')));

            $res = Db::table('admin')->where('id', $user_id)->update(['password' => $new_password]);

            if ($res || $new_password == $o_password) {
                $this->success('修改密码成功！', url('/admin'));
            } else {
                $this->error('修改密码失败！');
            }
        }

        $this->assign('username', Session::get('user.name'));

        return $this->fetch();
    }

}